package model

import (
	"cms/libs"
	"errors"
	"github.com/jinzhu/gorm"
	config "github.com/spf13/viper"
	"math"
)

type Recommend struct {
	gorm.Model
	Title  string `gorm:"column:title" json:"title" form:"title" validate:"required"`
	Key    string `gorm:"column:key" json:"key" form:"key" validate:"required"`
	Val    string `gorm:"column:val" json:"val" form:"val"`
	System string `gorm:"column:system" json:"system" form:"system"`
	Sort   uint   `gorm:"column:sort" json:"sort" form:"sort"`
}

func (this *Recommend) List(page int) ([]Recommend, int, int) {
	var data = []Recommend{}
	var totalCount int
	db := libs.DB

	limit := config.GetInt("pagination.PageSize")
	offset := (page - 1) * limit
	db.Find(&data).Count(&totalCount)
	db.Offset(offset).Limit(limit).Order("sort desc").Find(&data)
	totalPages := int(math.Ceil(float64(totalCount) / float64(limit)))
	return data, totalCount, totalPages
}

func (this *Recommend) ListAll() []Recommend {
	var data = []Recommend{}
	db := libs.DB
	db.Order("sort desc").Find(&data)
	return data
}

func (this *Recommend) Info(id uint) (Recommend, error) {
	var recommend Recommend
	db := libs.DB

	if db.Where("id = ?", id).First(&recommend).RecordNotFound() {
		return Recommend{}, errors.New("内容未找到")
	}
	return recommend, nil
}

func (this *Recommend) Add(postValues map[string][]string) error {
	var recommend Recommend
	db := libs.DB

	if err := libs.FormDecode(&recommend, postValues); err != nil {
		return err
	}
	if err := libs.Validate(recommend); err != nil {
		return err
	}
	if !db.Where("`key` = ? ", recommend.Key).First(&Recommend{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}
	recommend.System = "否"
	if err := db.Create(&recommend).Error; err != nil {
		return err
	}
	return nil
}

func (this *Recommend) Update(postValues map[string][]string) error {
	var recommend Recommend
	var recommend2 Recommend
	db := libs.DB

	if err := libs.FormDecode(&recommend, postValues); err != nil {
		return err
	}
	if err := libs.Validate(recommend); err != nil {
		return err
	}
	if !db.Where("`key` = ? and id != ?", recommend.Key, recommend.ID).First(&Recommend{}).RecordNotFound() {
		return errors.New("该标题已经存在")
	}
	if db.Where("id = ? ", recommend.ID).First(&recommend2).RecordNotFound() {
		return errors.New("未查询到内容id")
	}

	if recommend2.System == "是" {
		recommend.System = "是"
	} else {
		recommend.System = "否"
	}

	if err := db.Save(&recommend).Error; err != nil {
		return err
	}
	return nil
}

func (this *Recommend) Del(id uint) error {
	var recommend Recommend
	db := libs.DB

	if err := db.Where("id = ?", id).Delete(&recommend).Error; err != nil {
		return err
	}
	return nil
}
